package com.simoniu.first.servlet;

import com.simoniu.first.util.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

@WebServlet(name = "FileUploadServlet", value = "/upload")
@MultipartConfig(maxFileSize = 1000 * 1024 * 1024, maxRequestSize = 1000 * 1024 * 1024)

public class FileUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        System.out.println("上传用户：" + username);

        String savePathRoot = this.getServletContext().getRealPath("/WEB-INF/upload");
        System.out.println(savePathRoot);

        Collection<Part> parts = request.getParts();
        for (Part part : parts) {

            /*Collection<String> headerNames = part.getHeaderNames();
            for (String name : headerNames) {
                System.out.println(name);
            }*/

            //获得提交的名字
            String filename = part.getSubmittedFileName();
            System.out.println(filename);

            //对于不是上传文件的input会传来空值，或者你没有指定上传的文件也是null，这里过滤一下
            if (filename == null) {
                continue;
            }
            String fileUUIDName = FileUtils.makeFileName(filename);
            String saveDir = FileUtils.fileSave(fileUUIDName, savePathRoot);
            /*long size = part.getSize();*/

            //File.separator是自适应的windows和linux分隔符就是\\和/
            part.write(saveDir + File.separator + fileUUIDName);
            //删除临时文件
            part.delete();
        }
    }
}
